﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http.Description;
using Bronze.Components;
using Swashbuckle.Swagger;

namespace HuntingFishGame.CustomerApi.App_Start.Swagger
{
    /// <summary>
    /// api文档中显示枚举值
    /// </summary>
    public class EnumDocumentExtensions : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            foreach (var schemaDictionaryItem in swaggerDoc.definitions)
            {
                var schema = schemaDictionaryItem.Value;
                foreach (var propertyDictionaryItem in schema.properties)
                {
                    var property = propertyDictionaryItem.Value;
                    var propertyEnums = property.@enum;
                    if (propertyEnums != null && propertyEnums.Count > 0)
                    {
                        var enumDescriptions = new List<string>();

                        for (int i = 0; i < propertyEnums.Count; i++)
                        {
                            var enumOption = propertyEnums[i];
                            var member = enumOption.GetType().GetMember(enumOption.ToString(),BindingFlags.Public | BindingFlags.Static).SingleOrDefault();
                            var desc = ControllerSummaryFilter.GetEnumDescrition(member);
                            if (desc.IsNull())
                            {
                                desc = Enum.GetName(enumOption.GetType(), enumOption);
                            }

                            enumDescriptions.Add(string.Format("{0} : {1} ", (int)enumOption, desc));
                        }
                        property.description += string.Format(" ({0})", string.Join(", ", enumDescriptions.ToArray()));
                    }
                }
            }
        }

  
    }
}